﻿#if ToLua && UNITY_EDITOR

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

public class ToLuaWrapTool
{

    public static string EnPath = Application.dataPath + "/luaEnTemp/";

    [MenuItem("Lua/Build bundle files not jit encryption", false, 56)]
    public static void BuildNotJitBundles()
    {
        string[] files = Directory.GetFiles(LuaConst.luaDir, "*.lua", SearchOption.AllDirectories);
        if (!Directory.Exists(EnPath))
            Directory.CreateDirectory(EnPath);

        foreach (var item in files)
        {
            string str = File.ReadAllText(item);
            string newStr = EncryptionUtil.Encode(str);
            
            string dir = item.Replace(LuaConst.luaDir, "");
            dir = dir.TrimStart('/');
            dir = dir.TrimStart('\\');

            string fileName = Path.GetFileName(dir);
            string dirName = Path.GetDirectoryName(dir);

            string newDir = Path.Combine(EnPath, dirName);
            if (!Directory.Exists(newDir) && !string.IsNullOrEmpty(newDir))
                Directory.CreateDirectory(newDir);


            string filePath = Path.Combine(newDir, fileName);
            File.WriteAllText(filePath, newStr);


        }

        Debug.Log("加密完毕");
        AssetDatabase.Refresh();
    }


    [MenuItem("Lua/Build bundle files not jit Decryption", false, 57)]
    public static void DecryptionLua()
    {
        string[] files = Directory.GetFiles(EnPath, "*.lua", SearchOption.AllDirectories);


        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        foreach (var item in files)
        {
            string str = File.ReadAllText(item);
            string newStr = EncryptionUtil.Decode(str);


            int index1 = item.LastIndexOf(@"/");
            int index2 = item.LastIndexOf(@"\");
            int index = index1 > index2 ? index1 : index2;
            string fileName = item.Substring(index + 1);

            sb.AppendLine("File: " + fileName);
            sb.AppendLine(newStr);
            sb.AppendLine();
        }

        

        Debug.Log("解密完毕\n" + sb.ToString());
    }
}

#endif
